<template>
  <a-spin :spinning="msgLoading && requestTime === 0" :tip="spinTip">
    <div class="message">
      <div class="message-tabs">
        <a-tabs default-active-key="1" @change="getShowListNow">
        <a-tab-pane key="1" tab="未读" />
        <a-tab-pane key="2" tab="已读" />
      </a-tabs>
      </div>
      <div class="message-list">
        <img
          v-show="magList.length === 0 && !(msgLoading && requestTime === 0)"
          class="home-search-empty"
          src="~@/assets/img/empty.png"
        />
        <pull-to 
        :bottom-config="BOTTOM_DEFAULT_CONFIG"
        :bottom-load-method="infiniteHandler"
        :top-config="TOP_DEFAULT_CONFIG"
        :top-load-method="infiniteHandlerTop"
        ref="pullto">
          <message-list
            class="message-list-body"
            :dotString="1"
            :message-list="listShowNow"
            @click="messageBtnClick"
          />
            <!-- :message-list="magList" -->

        </pull-to>
      </div>
    </div>
  </a-spin>
</template>

<script>
/*eslint-disable*/
import { messageGet, messageAck } from "@/api/message";
import PullTo from "vue-pull-to";

export default {
  name: "Message",
  data() {
    return {
      /* [
        {
          title: "审批通过",
          createTime: "11-28 13:09:12",
          content:
            "您于2020-11-27 13:51:12提交的《绍兴市柯桥区财政局提交预算调剂申请》已审批通过",
          status: 0,
        },
        {
          title: "审批驳回",
          createTime: "11-28 13:09:12",
          content:
            "您于2020-11-27 13:51:12提交的《绍兴市柯桥区财政局提交预算调剂申请》已审批通过",
          status: 1,
        },
      ] */
      magList: [],
      requestTime:0,
      BOTTOM_DEFAULT_CONFIG:{
        pullText: '上拉加载',
        triggerText: '加载更多记录',
        loadingText: '加载中...',
        doneText: '加载完成',
        failText: '无数据',
        loadedStayTime: 400,
        stayDistance: 50,
        triggerDistance: 70
      },
      TOP_DEFAULT_CONFIG : {
        pullText: '下拉刷新', // 下拉时显示的文字
        triggerText: '释放更新', // 下拉到触发距离时显示的文字
        loadingText: '加载中...', // 加载中的文字
        doneText: '加载完成', // 加载完成的文字
        failText: '加载失败', // 加载失败的文字
        loadedStayTime: 400, // 加载完后停留的时间ms
        stayDistance: 50, // 触发刷新后停留的距离
        triggerDistance: 50 // 下拉刷新触发的距离
      },
      msgLoading: false,
      spinTip: "",
      limit: 10, // pageSize
      pageSize: 30,
      pageIndex: 1,
      total: 0,
      listShowNow:[],
      tabNow: 1
    };
  },
  computed: {
    getUnReaded() {
      let flag = false;
      const { magList } = this;
      if (magList && magList.length) {
        magList.map((item) => {
          if (item.isRead === 0) {
            flag = true;
          }
        });
      }
      return flag;
    },
    isNextPage() {
      if (this.total === 0) {
        return true;
      }
      const lastPage = Math.ceil(this.total / this.pageSize);

      return this.pageIndex <= lastPage;
    },
  },
  methods: {
    getIsReadedListNow(value){
      return this.magList.filter(item => item.isRead === value)
    },
    getShowListNow(value){
      this.tabNow = value
      this.listShowNow =  this.getIsReadedListNow(value - 1)
    },
    async infiniteHandlerTop(loaded){
      this.requestTime = 0
      this.pageIndex = 1
      await this.pageInit()
      loaded('done')
    },
    async infiniteHandler(loaded){
      const {isNextPage} = this 
      const flag = await this.loadMore()
      if (flag) {
        if (!isNextPage) {
          this.BOTTOM_DEFAULT_CONFIG.doneText = '没有更多数据拉'
        }else{
          this.BOTTOM_DEFAULT_CONFIG.doneText = '加载成功'
        }
        setTimeout(() => {
          loaded("done");//结束上拉
        }, 500);
      }else{
        this.BOTTOM_DEFAULT_CONFIG.failText = '没有更多数据拉'
        setTimeout(() => {
          loaded("fail");//结束上拉
        }, 500);
      }
    },
    scrollArivedBottom() {
      this.loadMore();
    },
    async loadMore() {
      this.pageIndex = this.pageIndex + 1;
      const flag = await this.pageInit("more");
      return Promise.resolve(flag)
    },
    messageBtnClick(item) {
      messageAck({ id: item.id }).then((res) => {
        if (res.code === 200 && res.success) {
          item.isRead ? "" : (item.isRead = 1);
          let params = item.params || "";
          if (!item.status) {
            params = params.replace(/showSPBtns=1/, "showSPBtns=0");
          }
          this.$router.push(`/detailPage${params}`);
        } else {
          this.$warning(res.message);
        }
      });
    },
    async pageInit(type = "", search = "") {
      let flag = false
      if (!this.isNextPage) {
        return;
      }
      this.msgLoading = true;
      this.spinTip = "加载中...";
      const requestData = {
        // order: "asc",
        // offset: (this.pageIndex - 1) * this.limit,
        // limit: this.limit,
        // "task.subject_^VLK": search,
        pageSize: this.pageSize,
        pageNum: this.pageIndex,
        userId: localStorage.getItem("userId"),
      };
      const magList = await this.messageGet(requestData);
      if (magList.code === 200 && magList.success) {
        flag = true
        this.spinTip = "加载成功...";
        if (magList.data.list && magList.data.list.length) {
          this.total = magList.data.total;
          if (type === "more") {
            this.magList = [
              ...this.magList,
              ...this.dealResList(magList.data.list),
            ];
          } else {
            this.magList = this.dealResList(magList.data.list);
          }
            this.listShowNow =  this.getIsReadedListNow(this.tabNow - 1)
        }
      } else {
        if (type === "more") {
          this.pageIndex = this.pageIndex - 1;
        }
        this.spinTip = magList.message;
      }
      setTimeout(() => {
        this.msgLoading = false;
        this.requestTime = 1
      }, 500);
      return Promise.resolve(flag)
    },
    copyDataList(data) {
      let res;
      const type = Object.prototype.toString.call(data);
      if (type.includes("Array")) {
        res = [];
      } else {
        res = {};
      }

      for (let key in data) {
        if (typeof res[key] === "object") {
          this.copyDataList(res[key]);
        } else {
          res[key] = data[key];
        }
      }

      return res;
    },
    dealResList(data) {
      const copyData = this.copyDataList(data);
      const statusMap = {
        agree: "审批通过",
        reject: "审批驳回",
        start: "开始流程",
      };
      copyData.forEach((item) => {
        item.title = statusMap[item.actionType] || "未知操作";
        item.status = item.title === "审批通过" ? 0 : 1;
        item.content = `${item.subject}已${item.title}`;
      });
      return copyData;
    },
    async messageGet(data) {
      return await messageGet(data);
    },
  },
  created() {
    const { pageInit } = this;
    pageInit();
  },
  components: {
    PullTo,
  },
  watch: {
    getUnReaded: {
      handler: function(flag) {
        this.$emit("messageReaded", flag);
      },
    },
  },
  // deactivated() {
  //   this.$destroy()
  // },
};
</script>
<style lang="less" scoped>
.message{
  width: 100%;
  height: 100vh;
  overflow: hidden;
  .message-tabs{
    background-color: #fff;
    /deep/ .ant-tabs-nav{
      width: 90%;
      >div{
        >div{
          width: 50%;
          text-align: center;
        }
      }
    }
  }
}
.message-list {
  overflow: hidden;
  width: 100%;
  height: calc(100vh - 50px - 45px);
  &::after {
    content: "";
    display: block;
    height: 66px;
  }
  .message-list-body {
    &::after {
      content: "";
      display: block;
      height: 10px;
    }
  }
}
.endline {
  padding: 0 9px;
  span {
    font-size: 10px;
    font-weight: 400;
    color: #999999;
  }
}
.home-search-empty {
  width: 121px;
  height: 131px;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -80%);
  display: flex;
  justify-content: center;
  align-items: center;
}
/deep/ .ant-tabs-bar{
  margin: 0;
}
</style>
